package kernel
import (
	"bytes"
	"encoding/json"
	"github.com/rs/zerolog/log"
	"io"
	"io/ioutil"
	"net/http"
	"time"
)

type HttpResult struct {
	Code float64
	Msg string
	Data string
}
//对接的api返回消息格式
type PhpResponse struct {
	Res int `json:"res"`
	Data string `json:"data"`
	Msg string `json:"msg"`
}

func Get(url string) (p *PhpResponse,error error) {
	client := http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		error = err
		return
	}
	defer resp.Body.Close()
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			error = err
			return
		}
	}
	response := result.String()
	if err := json.Unmarshal([]byte(response),p); err != nil{
		log.Error().Msgf("解析json错误:%s",err.Error())
	}
	return
}
// 发送POST请求
// url:请求地址，data:POST请求提交的数据,contentType:请求体格式，如：application/json
// content:请求放回的内容
func Post(url string, data interface{}, contentType string) (content string,error error) {
	jsonStr, _ := json.Marshal(data)
	body :=bytes.NewBuffer(jsonStr)
	req, err := http.NewRequest("POST", url,body )
	req.Header.Add("content-type", contentType)
	req.Header.Set("charset","UTF-8")
	if err != nil {
		error = err
		return
	}
	defer req.Body.Close()

	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		error = err
		return
	}
	defer resp.Body.Close()

	result, _ := ioutil.ReadAll(resp.Body)
	content = string(result)
	return
}